package cre.tomcat4.ch10.core;

import org.apache.catalina.*;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.deploy.LoginConfig;
import org.apache.catalina.deploy.SecurityConstraint;

public class SimpleContextConfig implements LifecycleListener {

    public void lifecycleEvent(LifecycleEvent event) {
        if (Lifecycle.START_EVENT.equals(event.getType())) {
            Context context = (Context) event.getLifecycle();

            authenticatorConfig(context);
            context.setConfigured(true);
        }
    }

    private void authenticatorConfig(Context context) {
        //是否有安全限制
        SecurityConstraint constraints[] = context.findConstraints();
        if (constraints == null || constraints.length == 0) {
            return;
        }
        //是否配置LoginConfig
        LoginConfig loginConfig = context.getLoginConfig();
        if (loginConfig == null) {
            loginConfig = new LoginConfig("NONE", null, null, null);
            context.setLoginConfig(loginConfig);
        }
        //一个管道只能有一个验证器阀
        Pipeline pipeline = ((StandardContext) context).getPipeline();
        if (pipeline != null) {
            Valve basic = pipeline.getBasic();
            if (basic instanceof Authenticator) {
                return;
            }

            Valve[] valves = pipeline.getValves();
            for (Valve valve : valves) {
                if (valve instanceof Authenticator) {
                    return;
                }
            }
        } else {
            return;
        }
        //  是否有领域对象
        Realm realm = context.getRealm();
        if (realm == null) {
            return;
        }
        //动态载入org.apache.catalina.authenticator.BasicAuthenticator，作为阀添加进管道
        try {
            String authenticatorName = "org.apache.catalina.authenticator.BasicAuthenticator";
            Class authenticatorClass = Class.forName(authenticatorName);
            Valve authenticator = (Valve) authenticatorClass.newInstance();
            ((StandardContext) context).addValve(authenticator);
            System.out.println("Add authenticator valve to Context");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}